﻿package com.xgr.wonderful.activity;

import java.util.Random;

import com.xgr.wonderful.activity.base.BaseActivity;
import com.xgr.wonderful.constant.Constant;
import com.xgr.wonderful.db.DatabaseUtil;
import com.xgr.wonderful.entity.User;
import com.easemob.EMCallBack;
import com.easemob.chat.EMChatManager;
import com.google.gson.Gson;
import com.xgr.wonderful.MainActivity;
import com.xgr.wonderful.R;
import com.xgr.wonderful.utils.HXUtils;
import com.xgr.wonderful.utils.HttpProxy;
import com.xgr.wonderful.utils.HttpProxy.IHttpRequestListener;
import com.xgr.wonderful.utils.LocalLikeRelationsUtils;
import com.xgr.wonderful.utils.LocalUserUtils;
import com.xgr.wonderful.utils.LogUtils;
import com.xgr.wonderful.utils.SettingUtils;
import com.xgr.wonderful.utils.ToastFactory;
import android.content.Intent;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.widget.RelativeLayout;
import android.widget.TextView;

/**
 * @date 2014-2-21 最好不用图片资源 ，加载 起来比较慢
 */
public class SplashActivity extends BaseActivity {
	
	private RelativeLayout rootLayout ;
	
	private HttpProxy httpProxy ;
	
	private TextView appTv ;
	
	Intent intent  = null;
	Bundle bundle = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//最好代码设置，在manifest中设置会影响到progressbar，不知道为什么
		requestWindowFeature(Window.FEATURE_NO_TITLE);
	    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
        WindowManager.LayoutParams.FLAG_FULLSCREEN);
	    
		setContentView(R.layout.activity_splash);
		
		rootLayout = (RelativeLayout)findViewById(R.id.splash_root) ;
		appTv = (TextView)findViewById(R.id.splash_apptext) ;
		initAppText() ;
		intent = getIntent();
		httpProxy = new HttpProxy() ;
		
	}
	private void  initAppText (){
		Random random = new Random();
		String str[] = getResources().getStringArray(R.array.apptext);
		//appTv.setText(str[random.nextInt(4)]);
		appTv.setText(str[random.nextInt(str.length)]) ;
		
	}
	@Override
	protected void onStart() {
		// Activity可能是可见了，但还不是可交互
		super.onStart();
	}
	
	@Override
	protected void onResume() {
		// Activity可交互(也不一定),动画应该在这是设置，在onCreate里面设置是有问题的
		super.onResume();
		AlphaAnimation animation = new AlphaAnimation(0.3f, 0.8f);
		animation.setDuration(2000);
		animation.setAnimationListener(new AnimationListener() {
			
			@Override
			public void onAnimationStart(Animation animation) {
				
			}
			
			@Override
			public void onAnimationRepeat(Animation animation) {
				
			}
			
			@Override
			public void onAnimationEnd(Animation animation) {
				if (sputil.isLogin()){
					//这种情况下也会进行一次登录，以保证用户是当前用户,实际上可以省去自己服务器的登录
					LogUtils.i(TAG, "islogin = true") ;
					loginWeiX() ;
				}else { //没有登录，要去WelcomeActivity中
					LogUtils.i(TAG, "islogin = false") ;
					redictToActivity(mContext, WelcomeActivity.class, null) ;
					finish();
				}
			}
		}) ;
		rootLayout.startAnimation(animation) ;
	}
	
	private void loginWeiX (){
		String deviceid = SettingUtils.getDeviceId(mContext) ;
		LocalUserUtils.getInstance().init(mContext) ;//使用前一定要初始化
		//下面的情况 下，可以只登录EMchat，不再登录自己的
		if (LocalUserUtils.getInstance().getLocalUser()!= null &&
				LocalUserUtils.getInstance().getLocalUser().getDeviceID().equals(deviceid)) {

			LocalLikeRelationsUtils.getInstance().buildLikeRelations(mContext);
			sputil.setLogin(true);

			String userid = String.valueOf(LocalUserUtils.getInstance()
					.getLocalUser().getID());
			//showProgressDialog("正在登录中...", true) ;
			loginEM(userid, userid);
		}else {
			httpProxy.getUserByDeviceid(deviceid, new IHttpRequestListener() {
				
				@Override
				public void OnHttpRequestSuccessful(String result, int errCode) {
					if (errCode == Constant.ERR_HTTP_REQUEST_SUCCESS){
						User mUser = new Gson().fromJson(result, User.class) ;
						if (mUser != null) {
							LocalUserUtils.getInstance().saveLocalUser(
									mContext ,mUser ) ;
							//取得数据，并保存
							LocalLikeRelationsUtils.getInstance().buildLikeRelations(mContext) ;
							sputil.setLogin(true) ;
							
							String userid = String.valueOf(
									LocalUserUtils.getInstance().getLocalUser().getID()) ;
							loginEM (userid , userid );
						}else {
							//说明 没有查询到用户，可能 是没有注册
							ToastFactory.getToast(mContext, "您还没有注册").show() ;
							redictToActivity(mContext, WelcomeActivity.class, null);
							finish() ;
						}
						
					}else if (errCode == Constant.ERR_HTTP_REQUEST_FAILURE) {
						//cancelProgressDialog() ;
						ToastFactory.getToast(mContext, result).show() ;
						LogUtils.i(TAG, "splash login fail") ;
						redictToActivity(mContext, WelcomeActivity.class, null);
						finish();
					}
				}
				
				@Override
				public void OnHttpRequestStart() {
					//showProgressDialog("正在登录中...", true) ;
				}
				
				@Override
				public void OnHttpRequestFailure(String info) {
					//cancelProgressDialog() ;
					ToastFactory.getToast(mContext, "请查看您的网络").show() ;
					LogUtils.i(TAG, "splash login fail info:"+ info) ;
					redictToActivity(mContext, WelcomeActivity.class, null);
				}
			}) ;
		}
	}
	/**
	 * 确保 一定是登录的
	 * @param userid
	 * @param pwd
	 */
	protected void loginEM(String userid, String pwd ) {
		EMChatManager.getInstance().login(userid, pwd, new EMCallBack() {
			@Override
			public void onSuccess() {
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						//cancelProgressDialog() ;
						//ToastFactory.getToast(mContext, "服务器登录成功").show() ;
						DatabaseUtil.getInstance().initConversationDao(mContext) ;
						HXUtils.EMLoadConversations();
						redictToActivity(mContext, MainActivity.class, bundle);
						finish() ;
					}
				}) ;
			}
			@Override
			public void onProgress(int arg0, String arg1) {
			}
			@Override
			public void onError(int arg0, String arg1) {
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						//cancelProgressDialog() ;
						ToastFactory.getToast(mContext, "请查看您的网络").show() ;
						//能到这样一步，应该注册过
						redictToActivity(mContext, WelcomeActivity.class, null) ;
						finish();
					}
				}) ;
			}
		}) ;
	}
	
}
